//
//  GuideManager.swift
//  GuidePage
//
//  Created by Mac on 2021/2/27.
//

import UIKit

fileprivate let CFBundleVersion = "CFBundleVersion"
fileprivate let VersionPath = NSHomeDirectory().appending("/Documents/Version.data")

class GuideManager {
    /// 展示的图片
    var images: [UIImage]!
    
    /// 进入的按钮图片
    var enterImage: UIImage!
    /// 默认显示
    var isShowPageControl: Bool = true
    
    static let share: GuideManager = {
        let tools = GuideManager()
        return tools
    }()

    fileprivate var guideWindow: UIWindow?
    
    func checkVersion() {
        let currentVersion = Bundle.main.infoDictionary?[CFBundleVersion] as? String
        let preVersion = try? String(contentsOfFile: VersionPath)
        if preVersion != currentVersion {
            showGuideView(currentVersion!)
        }else {
            dismissGuideView()
        }
    }
    
    func showGuideView(_ currentVersion: String) {
        guideWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
        guideWindow?.windowLevel = .statusBar
        
        let rootVC = GuideViewController()
        rootVC.images = images
        rootVC.enterImage = enterImage
        rootVC.isShowPageControl = isShowPageControl
        rootVC.dismissClosure = { [weak self] in
            try? currentVersion.write(toFile: VersionPath, atomically: true, encoding: .utf8)
            self?.dismissGuideView()
        }
        guideWindow?.rootViewController = rootVC
        guideWindow?.makeKeyAndVisible()
    }
    
    func dismissGuideView() {
        guideWindow?.isHidden = true
        guideWindow = nil
        images = nil
        enterImage = nil
    }
}
